const express = require('express')
const bodyParser = require('body-parser')
const { Wechaty } = require('wechaty')
const qrcodeTerminal = require('qrcode-terminal')
const axios = require('axios')

// const chessDomain = 'http://127.0.0.1:8080'
const chessDomain = 'https://chess.tblogs.cn'

// 实例化微信机器人
const wechatBot = Wechaty.instance(); // Global Instance
let wechatBotInstance = false
const wechatBotLogonoff = () => {
  return wechatBotInstance && wechatBot.logonoff()
}
wechatBot.on('scan', (qrcode, status) => {
  // 显示二维码到控制台
  qrcodeTerminal.generate(qrcode, { small: true })
  const url = `https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(qrcode)}`
  console.log(`扫描登录二维码: ${status}\n${url}`)
  axios.post(`${chessDomain}/admin/wechat-bot/qrcode`, { url: url })
    .then(data => { })
    .catch(error => console.error('扫码登录二维码推送失败', error.config.url, error.response))
})
  .on('login', user => console.log(`微信号[${user}]登录成功`))
  .on('logout', user => console.log(`微信号[${user}]已退出登录`))
  .on('message', message => {
    const fromUserName = message.from().name()
    const text = message.text()
    if (message.self()) { return }
    console.log(`Contact: ${fromUserName} Type: ${message.type()}`)
    const msgType = [];
    msgType[wechatBot.Message.Type.Attachment] = true
    msgType[wechatBot.Message.Type.Text] = true
    msgType[wechatBot.Message.Type.Url] = true
    if (!msgType[message.type()]) { return }
    const room = message.room()
    if (room) {
      room.topic().then(topic => {
        console.log(`Room: ${topic} Contact: ${fromUserName} To: ${topic} Text: ${text}`)
        axios.post(`${chessDomain}/wechat-bot/message`, {
          room: { topic: topic },
          fromUserName: fromUserName,
          toUserName: topic,
          msgType: message.type(),
          content: text
        }).then(data => { }).catch(error => console.error('微信消息推送失败', error.config.url, error.response))
      })
    } else {
      console.log(`Contact: ${fromUserName} To: ${message.to().name()} Text: ${text}`)
    }
  })

// 创建HTTP服务器
var app = express()
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: false }))

app.all('*', (request, response, next) => {
  response.header('Access-Control-Allow-Origin', '*')
  response.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  response.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  response.header('X-Powered-By', '1.0.0')
  response.header('Content-Type', 'application/json;charset=utf-8')
  if (wechatBotLogonoff() || request.path === '/login') {
    next()
  } else {
    response.status(422).json({ message: '请先登录' })
  }
})

// 机器人是否登录
/*
curl -i -X POST \
   -H "Content-Type:application/json" \
 'http://127.0.0.1:58080/alive'
*/
app.post('/alive', (request, response, next) => {
  response.status(200).json(wechatBotLogonoff())
})
// 启动机器人并登录
/*
curl -i -X POST \
   -H "Content-Type:application/json" \
 'http://127.0.0.1:58080/login'
*/
app.post('/login', (request, response, next) => {
  if (wechatBotLogonoff()) {
    response.status(422).json({ message: '机器人已登录,请先退出' })
  } else {
    wechatBot.start()
      .then(() => {
        wechatBotInstance = true
        console.log('正在请求登录二维码,请稍候...')
      })
      .catch(e => console.error(e))
    response.end()
  }
})
// 退出机器人登录状态并关闭机器人
/*
curl -i -X POST \
   -H "Content-Type:application/json" \
 'http://127.0.0.1:58080/logout'
*/
app.post('/logout', (request, response, next) => {
  wechatBot.logout().then(() => {
    wechatBot.stop()
  }).catch(error => {
    wechatBot.stop()
  })
  response.end()
})
// 接收第三方请求发送信息
/*
curl -i -X POST \
   -H "Content-Type:application/json" \
   -d \
'{"room":{"topic":"改个名字"},"content":"发送信息"}' \
 'http://127.0.0.1:58080/message'
*/
app.post('/message', (request, response, next) => {
  const body = request.body
  console.log('请求参数：', body)
  wechatBot.Room.find({ topic: body.room.topic })
    .then(room => {
      room.say(body.content)
      response.end()
    }).catch(error => {
      response.status(422).json({ message: `未找到聊天室${body.room.topic}` })
    })
})


// 服务监听
var server = app.listen(58080, () => {
  var host = server.address().address
  var port = server.address().port
  console.log('服务已启动，访问地址为 http://%s:%s', host, port)
})

